<script setup lang="tsx">
import Write from './components/Write.vue'
import Material from './components/Material.vue'
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { Dialog } from '@/components/Dialog'
import { Table } from '@/components/Table'
import { nextTick, onMounted, reactive, ref, unref } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { useRoute, useRouter } from 'vue-router'
import { useEventBus } from '@/hooks/event/useEventBus'
import { Form, FormSchema } from '@/components/Form'
import {
  ElButton,
  ElCheckbox,
  ElCheckboxGroup,
  ElCol,
  ElCollapse,
  ElCollapseItem,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElRow,
  ElTag
} from 'element-plus'
import { addFemaleApi, getFemaleApi, putFemaleApi, putFemaleVersionApi } from '@/api/check/female'
import { getFeatureListApi } from '@/api/check/feature'
import { Icon } from '@/components/Icon'
import { TableColumn } from '@/components/Table'
import { FeatureType } from '@/api/check/feature/types'
import { FemaleType, FemaleWriteType } from '@/api/check/female/types'
import { getParamListApi } from '@/api/check/param'
import { watch } from 'fs'

const { emit } = useEventBus()

const { push, go } = useRouter()
const route = useRoute()

const { t } = useI18n()

const schema = reactive<FormSchema[]>([
  {
    field: 'part_no',
    label: '材料/零件图号',
    colProps: {
      span: 6
    },
    formItemProps: {
      slots: {
        default: (data) => {
          return (
            <ElInput
              v-model={data.part_no}
              placeholder="请输入"
              v-slots={{
                append: () => (
                  <ElButton onClick={() => (dialogVisible.value = true)}>
                    <Icon icon="ep:circle-plus" />
                  </ElButton>
                )
              }}
            />
          )
        }
      }
    }
  },
  {
    field: 'part_name',
    label: '材料/零件名称',
    colProps: {
      span: 6
    },
    component: 'Input'
  },
  {
    field: 'material_no',
    label: '物料编号',
    colProps: {
      span: 6
    },
    component: 'Input'
  },
  {
    field: 'product_type',
    label: '型号',
    colProps: {
      span: 6
    },
    component: 'Input'
  },
  {
    field: 'material',
    label: '材料类型',
    colProps: {
      span: 6
    },
    component: 'Input'
  },
  {
    field: 'material_type',
    label: '物料类型',
    colProps: {
      span: 6
    },
    component: 'Input'
  },

  {
    field: 'is_life_limit',
    label: '是否限寿件',
    colProps: {
      span: 6
    },
    component: 'Select',
    componentProps: {
      options: [
        {
          label: '是',
          value: true
        },
        {
          label: '否',
          value: false
        }
      ]
    }
  },
  {
    field: 'life_limit_req',
    label: '限寿要求',
    colProps: {
      span: 6
    },
    component: 'Input'
  },
  {
    field: 'is_sampling',
    label: '抽检',
    colProps: {
      span: 6
    },
    component: 'Select',
    componentProps: {
      options: [
        {
          label: '是',
          value: true
        },
        {
          label: '否',
          value: false
        }
      ]
    }
  },
  {
    field: 'plan_remark',
    label: '计划备注',
    colProps: {
      span: 6
    },
    component: 'Input'
  },
  {
    field: 'required_dimension',
    label: '要求尺寸',
    colProps: {
      span: 6
    },
    component: 'Input'
  },
  {
    field: 'pclr_size',
    label: '试样规格/尺寸',
    colProps: {
      span: 6
    },
    component: 'Input'
  },
  {
    field: 'pclr_quantity',
    label: '试样数量',
    colProps: {
      span: 6
    },
    component: 'Input'
  },
  {
    field: 'remark',
    label: '备注',
    colProps: {
      span: 6
    },
    component: 'Input'
  },
  {
    field: '',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: (data) => {
          const tableColumns1 = reactive<TableColumn[]>([
            {
              field: 'selection',
              fixed: true,
              type: 'selection',
              width: 80
            },
            {
              field: 'index',
              label: t('common.index'),
              type: 'index',
              minWidth: 80,
              fixed: true
            },
            {
              field: 'project',
              label: '检验项目',
              minWidth: 120
            },
            {
              field: 'detail',
              label: '检验明细',
              minWidth: 120,
              slots: {
                default: (scope) => <ElInput v-model={scope.row!.detail} />
              }
            },
            {
              field: 'attachment',
              label: '检验图片',
              minWidth: 120,
              slots: {
                default: (scope) => <ElInput v-model={scope.row!.attachment} />
              }
            },
            {
              field: 'action',
              label: '操作',
              minWidth: 120,
              slots: {
                default: (scope) => <ElButton>新增</ElButton>
              }
            }
          ])
          const tableColumns2 = reactive<TableColumn[]>([
            {
              field: 'selection',
              fixed: true,
              type: 'selection',
              width: 80
            },
            {
              field: 'index',
              label: t('common.index'),
              type: 'index',
              minWidth: 80,
              fixed: true
            },
            {
              field: 'part_no',
              label: '材料/零件图号',
              minWidth: 120
            },
            {
              field: 'characteristic',
              label: '特征',
              minWidth: 120
            },
            {
              field: 'dimension',
              label: '尺寸',
              minWidth: 120
            },
            {
              field: 'irr',
              label: '初始可靠值',
              minWidth: 120
            },
            {
              field: 'grade',
              label: '等级',
              minWidth: 120
            }
          ])
          const handleCheck = (v, item, type) => {
            if (v) {
              data.contents.push({
                content_type: type,
                project: item.param_name,
                detail: item.param_detail ? item.param_detail.split(';').map(() => '') : ''
              })
            } else data.contents = data.contents.filter((v) => v.project != item.param_name)
            console.log(data.contents)
          }
          const foundContent = (type, item) => {
            const contents = data.contents.filter(
              (v) => v.content_type == type && v.project == item.param_name
            )
            return contents ? contents[0] : undefined
          }
          return (
            <ElCollapse accordion class="w-full">
              <ElCollapseItem title="零件/材料标记" name="1">
                <ElForm labelWidth="auto" labelPosition="right">
                  <ElRow gutter={20}>
                    <ElCol span={8}>
                      <ElFormItem label="图号/件号/材料牌号">
                        <ElInput v-model={data.draw_no} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="更改字母">
                        <ElInput v-model={data.rev_letter} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="状态">
                        <ElInput v-model={data.temper} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="规范/标准">
                        <ElInput v-model={data.spec_stan} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="规范/标准版次">
                        <ElInput v-model={data.spec_stan_rev} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="工艺材料编号">
                        <ElInput v-model={data.zpm_cpm} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="型别">
                        <ElInput v-model={data.typing} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="类别/组合物别">
                        <ElInput v-model={data.classing} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="级别">
                        <ElInput v-model={data.grade} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="形态/形式">
                        <ElInput v-model={data.form} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="规格">
                        <ElInput v-model={data.size} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="色号">
                        <ElInput v-model={data.color} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="性能要求">
                        <ElInput v-model={data.special_property} />
                      </ElFormItem>
                    </ElCol>
                  </ElRow>
                </ElForm>
              </ElCollapseItem>
              <ElCollapseItem title="检验/验证特性" name="2">
                <ElButton class="mb-10px">增加</ElButton>
                <Table data={data.insp_contents} columns={tableColumns1}></Table>
              </ElCollapseItem>
              <ElCollapseItem title="实验要求" name="3">
                <ElForm labelWidth="auto" labelPosition="right" class="ml-10">
                  {params.value.tests?.map((item) => {
                    const content = foundContent('实验要求', item)
                    return (
                      <div class="flex mb-10px">
                        <ElCheckbox
                          label={item.param_name}
                          onChange={(v) => handleCheck(v, item, '实验要求')}
                          checked={Boolean(content)}
                        />
                        {item.param_detail?.split(';').map((detail, i) => {
                          return (
                            <div class="flex items-center	ml-10px">
                              {content ? (
                                <ElInput v-model={content.detail[i]} placeholder={detail} />
                              ) : (
                                <ElInput placeholder={detail} />
                              )}
                            </div>
                          )
                        })}
                      </div>
                    )
                  })}
                </ElForm>
              </ElCollapseItem>
              <ElCollapseItem title="限制要求" name="4">
                <ElForm labelWidth="auto" labelPosition="right" class="ml-10">
                  {params.value.limits?.map((item) => {
                    const content = foundContent('限制要求', item)
                    return (
                      <div class="flex mb-10px">
                        <ElCheckbox
                          label={item.param_name}
                          onChange={(v) => handleCheck(v, item, '限制要求')}
                          checked={Boolean(content)}
                        />
                        {item.param_detail?.split(';').map((detail, i) => {
                          return (
                            <div class="flex items-center	ml-10px">
                              {content ? (
                                <ElInput v-model={content.detail[i]} placeholder={detail} />
                              ) : (
                                <ElInput placeholder={detail} />
                              )}
                            </div>
                          )
                        })}
                      </div>
                    )
                  })}
                </ElForm>
              </ElCollapseItem>
              <ElCollapseItem title="ASR检验信息" name="5">
                <Table data={params.value.features} columns={tableColumns2} class="w-full" />
              </ElCollapseItem>
              <ElCollapseItem title="限寿要求" name="6">
                <ElForm labelWidth="auto" labelPosition="right" class="ml-10">
                  <ElRow gutter={20}>
                    <ElCol span={2}>
                      <ElCheckbox v-model={data.is_life_limit} label="是否限寿件" />
                    </ElCol>
                    <ElCol span={6}>
                      <ElFormItem label="工程要求">
                        <ElInput v-model={data.life_limit_req} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={6}>
                      <ElFormItem label="基准日期">
                        <ElInput v-model={data.life_limit_date} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={6}>
                      <ElFormItem label="库房存储期限">
                        <ElInput v-model={data.life_limit_period} />
                      </ElFormItem>
                    </ElCol>
                  </ElRow>
                </ElForm>
              </ElCollapseItem>
            </ElCollapse>
          )
        }
      }
    }
  }
])

const currentRow = ref<FemaleWriteType>({
  id: undefined,
  status: undefined,
  version: undefined,
  part_no: undefined,
  asr_features: [] as FeatureType[],
  contents: [],
  test_contents: [],
  limit_contents: []
})

const materialRef = ref<ComponentRef<typeof Material>>()
const dialogVisible = ref(false)

const getFemale = async (data) => {
  if (data.id) {
    const res = await getFemaleApi(data)
    if (res) {
      currentRow.value = res.data
    }
  } else if (data.part_no) {
    currentRow.value = { ...data }
    const res = await getFeatureListApi(data)
    if (res) {
      currentRow.value.asr_features = res.data
    }
  } else currentRow.value.asr_features = []
}

const onSelectPart = async () => {
  const write = unref(materialRef)
  const formData = await write?.submit()
  if (formData) await getFemale(formData)
  dialogVisible.value = false
}

const writeRef = ref<ComponentRef<typeof Write>>()

const loading = ref(false)

const save = async (data: Recordable | undefined) => {
  const formData = await unref(writeRef)?.submit()
  if (formData) {
    try {
      loading.value = true
      const res = currentRow.value.id
        ? await putFemaleApi({ ...formData, ...data })
        : await addFemaleApi({ ...formData, ...data })
      if (res) {
        await getFemale(formData)
      }
    } finally {
      loading.value = false
    }
  }
}

const upVersion = async () => {
  const formData = await unref(writeRef)?.submit()
  if (formData) {
    try {
      loading.value = true
      if (!currentRow.value.id) {
        ElMessage.warning('未保存的母本，不可升版')
        return
      }
      const res = await putFemaleVersionApi(formData)
      if (res) {
        await getFemale(formData)
      }
    } finally {
      loading.value = false
    }
  }
}

const params = ref<Recordable>({
  tests: [],
  limits: [],
  features: [],
  insps: []
})

const getParams = async () => {
  const filterParamsByType = (params, type: string) => {
    if (params) return params.filter((item) => item.param_type == type)
    else return [] as any[]
  }
  const res = await getParamListApi({ limit: 0 })
  if (res) {
    params.value.tests = filterParamsByType(res.data, '实验要求')
    params.value.limits = filterParamsByType(res.data, '限制要求')
  }

  if (currentRow.value.part_no) {
    const res1 = await getFeatureListApi({ limit: 0, part_no: currentRow.value.part_no })
    if (res1) {
      params.value.features = res1.data
    }
  }
}

onMounted(async () => {
  const params = {
    ...route.params,
    ...route.query
  }
  await getFemale(params)
  await getParams()
})
</script>

<template>
  <ContentDetailWrap :title="t('common.add')">
    <Write ref="writeRef" :form-schema="schema" :current-row="currentRow" />
    <template #header>
      <div class="flex justify-between items-center">
        <div>
          <ElButton @click="go(-1)">
            {{ t('common.back') }}
          </ElButton>
          <ElButton
            type="primary"
            :loading="loading"
            @click="save"
            v-if="currentRow.status != '启用'"
          >
            {{ t('common.save') }}
          </ElButton>
          <ElButton
            type="primary"
            :loading="loading"
            @click="() => save({ status: '启用' })"
            v-if="currentRow.status != '启用'"
          >
            {{ '启用' }}
          </ElButton>
          <ElButton
            type="primary"
            :loading="loading"
            @click="upVersion"
            v-if="currentRow.status == '启用'"
          >
            {{ '升版' }}
          </ElButton>
        </div>
        <div class="mr-10">
          <ElTag type="success">{{ currentRow?.status ?? '未创建' }}</ElTag>
          <ElTag type="success">{{ 'V' + (currentRow?.version ?? '1') }}</ElTag>
        </div>
      </div>
    </template>
  </ContentDetailWrap>

  <Dialog v-model="dialogVisible">
    <Material ref="materialRef" />
    <template #footer>
      <ElButton type="primary" @click="onSelectPart">
        {{ t('common.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('common.close') }}</ElButton>
    </template>
  </Dialog>
</template>

<style lang="less" scoped>
:deep(.el-collapse-item__header) {
  display: unset;
  font-size: 16px;
  font-weight: 600;
  background-color: #f2f2f2;
  margin-bottom: 20px;
}
:deep(.el-form-item) {
  margin-bottom: 18px;
}
:deep(.content_wrap .el-form-item) {
  margin-bottom: 0;
}
</style>
@/hooks/event/useEventBus
